package com.fingerth.crawler.ui

import com.fingerth.crawler.R
import com.fingerth.crawler.base.BaseAct
import com.fingerth.crawler.databinding.ActivityMainBinding
import com.fingerth.crawler.listener.SimpleTabSelectedListener
import com.fingerth.crawler.ui.adapter.HomeFragmentAdapter
import com.fingerth.crawler.ui.fragment.CrawlerNovelFragment
import com.fingerth.crawler.ui.fragment.EmptyFragment
import com.fingerth.crawler.utils.ToastUtils
import com.fingerth.crawler.views.tabview.HomeTabView

class MainActivity : BaseAct<ActivityMainBinding>() {
    private val tabSize = 3
    private lateinit var fragmentAdapter: HomeFragmentAdapter
    override fun initStatusBar() {}

    override fun initView() {
        permissionUtils.checkAllPermissions(this)
        repeat(tabSize) { vBinding.tabLayout.addTab(vBinding.tabLayout.newTab().apply { customView = HomeTabView(this@MainActivity, position = it) }) }
        vBinding.tabLayout.addOnTabSelectedListener(SimpleTabSelectedListener { tabSelect(it.position) })
        fragmentAdapter = HomeFragmentAdapter(supportFragmentManager, R.id.frame_layout) {
            when (it) {
                0 -> CrawlerNovelFragment()
                1 -> EmptyFragment()
                2 -> EmptyFragment()
                else -> EmptyFragment()
            }
        }
    }

    private fun tabSelect(pos: Int) {
        repeat(tabSize) { (vBinding.tabLayout.getTabAt(it)?.customView as? HomeTabView)?.setSelect(pos == it) }
        fragmentAdapter.changeFragment(pos)
    }

    private var exitTime: Long = 0

    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtils.showToast(this, "再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else super.onBackPressed()
    }

}